package com.yeyks.rocketmq.service.customer;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.yeyks.common.dto.mq.GrabTheOrderSuccessWebsocketMessage;
import com.yeyks.common.em.WebSocketTypeEnum;
import com.yeyks.common.utils.FormatUtils;
import com.yeyks.commonReference.append.rocketmq.pojo.RocketMQWebsocketBasePojo;
import com.yeyks.commonReference.append.rocketmq.service.producer.MQProducerService;
import com.yeyks.commonReference.service.config.ConfigService;
import com.yeyks.order.dal.domain.OrderPickRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author fuchangshuai
 * @date 2019/08/09 16:06
 */
@Slf4j
@Component
public class CommonSendService {
    @Autowired
    private ConfigService configService;
    @Autowired
    private MQProducerService mqProducerService;

    /**
     * 发送抢单失败的消息
     *
     * @param failOrderPickRecords
     */
    public void sendFailMessage(List<OrderPickRecord> failOrderPickRecords, Map<String, String> failMap) {
        if (null == failOrderPickRecords || failOrderPickRecords.size() == 0) {
            return;
        }
        try {
            if (null == failMap || failMap.size() == 0) {
                GrabTheOrderSuccessWebsocketMessage robOrderMsg = configService.getHotelRobOrderMsg();
                String phone = failOrderPickRecords.get(0).getPhone();
                if (null != phone) {
                    phone = FormatUtils.phoneHide(phone);
                }
                String price = FormatUtils.fenToYuan(failOrderPickRecords.get(0).getUserShowPrice());
                String failMsg = FormatUtils.formatTemplate(robOrderMsg.getFailMsg(), ImmutableMap.of("phone", phone, "price", price));
                failMap = ImmutableMap.of("failMsg", failMsg);
            }
            Set<OrderPickRecord> set = new TreeSet<>(Comparator.comparing(OrderPickRecord::getOperatorId));
            set.addAll(failOrderPickRecords);
            List<OrderPickRecord> collect = Lists.newArrayList(set);
            //未抢单成功的酒店
            for (OrderPickRecord orderPickRecord : collect) {
                RocketMQWebsocketBasePojo pojo = new RocketMQWebsocketBasePojo();
                pojo.setType(WebSocketTypeEnum.ROB_ORDER_RESULT.value());
                pojo.setUserId(orderPickRecord.getOperatorId());
                pojo.setBody(JSONUtil.toJsonStr(failMap));
                mqProducerService.sendWebsocketMsg(pojo);
                //发送mq让B端监听
                mqProducerService.sendRobResultMsg(pojo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("给酒店发送抢单成功或者抢单失败异常：failOrderPickRecords = {}", failOrderPickRecords);
        }
    }
}
